<?php

namespace app\admin\model\share;

use addons\shopro\model\User;
use app\common\model\AdvertPriceLog;
use app\common\model\ScoreLog;
use app\common\model\ShareUserRoleLog;
use app\common\model\StockLog;
use app\common\model\UserChangeLog;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;
use think\Exception;
use addons\shopro\model\Order;
use app\common\model\ShareConfig;
use app\admin\model\share\Reward as ShareReward;
use \app\admin\model\share\Money as ShareMoney;
use app\common\model\MoneyLog;
use \think\Log as Logs;
use app\common\library\Auth;
use app\admin\model\exchange\Code;
use function MongoDB\BSON\fromJSON;

class ShareUser extends Model
{
    // 表名
    protected $table = 'share_user';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    /**
     * 注册绑定上下级关系
     */
    public function add_share($parent_id, $user_id)
    {
        $user = self::get(['user_id' => $user_id]);
        if (empty($user)) {
            $share_user = new ShareUser();
            $share_user->inviter_id = $parent_id;
            $share_user->user_id = $user_id;
            $temp_parent_id = $this->get_parent_id_two($parent_id);
            $share_user->parent_id = $temp_parent_id;
            $share_user->addtime = time();
            if ($temp_parent_id == 0 && $parent_id != 0) {
                return 0;
            } else {
                $share_user->save();
                return 1;
            }
        } else {
            return 1;
        }
    }

    /**
     * 查找下3层是否绑定
     */
    public function get_parent_id($parent_id)
    {
        $user_flags = \db('share_user_flags')->where('user_id', $parent_id)->value('user_flags');
        $parent_user = self::where(['parent_id' => $parent_id])->select();
        if (count($parent_user) < 3) {
            return array($parent_id, count($parent_user)); // 本身 a
        } else {
            $temp_arr = array();
            foreach ($parent_user as $key => $value) {
                //如果是独立分割，并且和上级不是一个网体，则忽略
                \think\Log::error(json_encode([$user_flags, $value['user_flags']]));
                if ($this->is_not_team($user_flags, $value['user_flags'])) continue;

                $temp_user1 = self::where(['parent_id' => $value['user_id']])->select();
                if (count($temp_user1) < 3) {
                    return array($value['user_id'], count($temp_user1)); // 下一级 b
                } else {
                    $temp_arr[] = $value['user_id'];
                }
            }
            $temp_arr2 = array();
            $parent_user2 = self::where('parent_id', 'in', $temp_arr)->select();
            foreach ($parent_user2 as $key => $value) {
                //如果是独立分割，并且和上级不是一个网体，则忽略
                if ($this->is_not_team($user_flags, $value['user_flags'])) continue;

                $temp_user3 = self::where(['parent_id' => $value['user_id']])->select();
                if (count($temp_user3) < 3) {
                    return array($value['user_id'], count($temp_user3)); // 下一级 c
                } else {
                    $temp_arr2[] = $value['user_id'];
                }
            }

            $parent_user3 = self::where('parent_id', 'in', $temp_arr2)->select();
            foreach ($parent_user3 as $key => $value) {
                //如果是独立分割，并且和上级不是一个网体，则忽略
                if ($this->is_not_team($user_flags, $value['user_flags'])) continue;

                $temp_user4 = self::where(['parent_id' => $value['user_id']])->select();
                if (count($temp_user4) < 3) {
                    return array($value['user_id'], count($temp_user4)); // 下一级 d
                }
            }

            return 0;
        }
    }
    public function get_parent_id_two($parent_id)
    {
        $user_flags = \db('share_user_flags')->where('user_id','in', $parent_id)->value('user_flags');
        $temp_arr = [];
        $parent_user = self::where('parent_id' ,'in', $parent_id)->select();
        //if(!$parent_user) return 0;
        if (count($parent_user) < 3) {
            return array($parent_id, count($parent_user)); // 本身 a
        } else {

            $temp_arr = array();
            foreach ($parent_user as $key => $value) {
                //如果是独立分割，并且和上级不是一个网体，则忽略
                \think\Log::error(json_encode([$user_flags, $value['user_flags']]));
                if ($this->is_not_team($user_flags, $value['user_flags'])) continue;

                $temp_user1 = self::where(['parent_id' => $value['user_id']])->select();
                if (count($temp_user1) < 3) {
                    return array($value['user_id'], count($temp_user1)); // 下一级 b
                }else {
                    $temp_arr[] = $value['user_id'];
                }
            }
        }
       return $this->get_parent_id_two($temp_arr);
    }

    protected function is_not_team($user_flags, $sub_user_flags)
    {
        if ($user_flags && !empty($sub_user_flags) && $sub_user_flags != $user_flags)
            return true;

        return false;
    }

    /**
     * 注册绑定上下级关系
     */
    public function add_user($parent_id, $user_id, $inviter_id, $role_type)
    {
        $user = self::get(['user_id' => $user_id]);
        if (empty($user)) {
            $puser = \db("share_user_flags")->where('user_id', $parent_id)->find();

            $share_user = new ShareUser();
            $share_user->inviter_id = $inviter_id;
            $share_user->user_id = $user_id;
            $share_user->parent_id = $parent_id;
            $share_user->role_type = $role_type;
            $share_user->role_url = $this->add_promotion($parent_id);
            $share_user->addtime = time();
            $share_user->save();

            if (isset($puser)) {
                \db("share_user_flags")->insert([
                    'user_id' => $user_id,
                    'user_flags' => $puser['user_flags'],
                    'addtime' => time(),
                ]);
            }

//            (new CommonShare())->parent_promotin($user_id);

            return 0;
        } else {
            return 1;
        }
    }

    public function add_promotion($user_id, $role_url = '')
    {
        $user = self::get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) {
            return $role_url;
        }

        $role_url = $role_url . '/' . $user->user_id;

        // 最高等级结束
        if ($user->role == 7) {
            return $role_url;
        }

        if (strpos($role_url, '/' . $user_id . '/') > 0) {
            return '/###/' . $role_url;
        }

        return $this->add_promotion($user->parent_id, $role_url);
    }

    // 上级用户晋级
    public function promotion_save($user_id, $role, $role_type)
    {
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户

        if (empty($user)) {
            return 0;
        }
        // 最高等级结束
        if ($user->role == 7) {
            return 0;
        }
        file_put_contents('ts111.txt',$role_type."_".$role);
        if ($role_type == 1) {
            $temp_role = $user->role1;
            if ($temp_role < $role) {
                $user->role1 = $role;
                $user->save();
            }
        }

        if ($role_type == 2) {
            $temp_role = $user->role2;
            if ($temp_role < $role) {
                $user->role2 = $role;
                $user->save();
            }
        }

        if ($role_type == 3) {
            $temp_role = $user->role3;
            if ($temp_role < $role) {
                $user->role3 = $role;
                $user->save();
            }
        }

        // 上级用户
        $temp_user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if ($temp_user->role >= 1 && $temp_user->role1 >= $temp_user->role &&
            $temp_user->role2 >= $temp_user->role &&
            $temp_user->role3 >= $temp_user->role) {
            $temp_add_role = bcadd($user->role, 1);
            $sharerule = Db::name("config")->where(['name' => 'sharerule','group'=>'basic'])->find();
            $is_rule = empty($sharerule) ? 'amount' : $sharerule['value'];
            if($is_rule == 'amount'){
                $ShareConfig = ShareConfig::where(['role' => $temp_add_role, 'type' => 2])->find();
                if (!empty($ShareConfig) && $user->amount >= (int)$ShareConfig['reward']) {
                    $temp_user->role = bcadd($user->role, 1);
                    $temp_user->save();
                    ShareUserRoleLog::create(['user_id' => $user_id, 'before_role' => $user->role, 'after_role' => $temp_user->role, 'before_amount' => $user->amount, 'after_amount' => $user->amount, 'memo' => '自动变更级别']);

                }
            } else {
                $ShareConfig = ShareConfig::where(['role' => $temp_add_role, 'type' => 7])->find();
                if (!empty($ShareConfig) && $user->achievement >= (int)$ShareConfig['reward']) {
                    $temp_user->role = bcadd($user->role, 1);
                    $temp_user->save();
                    ShareUserRoleLog::create(['user_id' => $user_id, 'before_role' => $user->role, 'after_role' => $temp_user->role, 'before_amount' => $user->amount, 'after_amount' => $user->amount, 'memo' => '自动变更级别']);
                }
            }
        }
        return $this->promotion_save($user->parent_id, $temp_user->role, $user->role_type);
    }

    public function user()
    {
        return $this->belongsTo(\app\admin\model\User::class, 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * [lock_money 鎖定餘額]
     * @param ShareUser $mod [description]
     * @param  [type]     $money [description]
     * @return [type]            [description]
     * @since  2022-10-12
     */
    public function lock_money(ShareUser $mod, $money, $with_type = 0)
    {
        if ($with_type == 1) {//老余额
            $mod->old_price -= $money;
            $mod->lock_money += $money;
        } elseif ($with_type == 2) {//广告收益
            $mod->advert_price -= $money;
            $mod->lock_money += $money;
        } elseif ($with_type == 3) {//
            $mod->lp_price -= $money;
            $mod->lock_money += $money;
        } else {//新余额
            $mod->price -= $money;
            $mod->lock_money += $money;
        }
        $mod->save();
    }

    const UNLOCK_MONEY_TRUE = true;
    const UNLOCK_MONEY_FALSE = false;

    /**
     * [unlock_money description]
     * @param ShareUser $mod [description]
     * @param  [type]     $money  [description]
     * @param boolean $return [余额是否要返回]
     * @return [type]             [description]
     * @since  2022-09-30
     */
    public function unlock_money(ShareUser $mod, $money, $return = false, $staff = "0", $with_type = 0)
    {
        $mod->lock_money -= $money;
        if ($return) {

            if ($staff == 2) {
                if ($with_type == 1) {

                    MoneyLog::create(['user_id' => $mod->user_id, 'money' => $money, 'before' => $mod->old_price, 'after' => $mod->old_price + $money, 'type' => 6, 'memo' => '提现测试', 'is_old' => 1]);
                    $mod->old_price += $money;
                } elseif ($with_type == 2) {

                    AdvertPriceLog::create(['user_id' => $mod->user_id, 'money' => abs($money), 'before' => $mod->advert_price, 'after' => $mod->advert_price + $money, 'type' => 3, 'memo' => '提现测试']);
                    $mod->advert_price += $money;
                }elseif ($with_type == 3) {

                    MoneyLog::create(['user_id' => $mod->user_id, 'money' => $money, 'before' => $mod->lp_price, 'after' => $mod->lp_price + $money, 'type' => 6, 'memo' => '提现测试', 'is_old' => 2]);
                    $mod->lp_price += $money;
                } else {

                    MoneyLog::create(['user_id' => $mod->user_id, 'money' => $money, 'before' => $mod->price, 'after' => $mod->price + $money, 'type' => 6, 'memo' => '提现测试']);
                    $mod->price += $money;
                }
            } else {
                if ($with_type == 1) {

                    MoneyLog::create(['user_id' => $mod->user_id, 'money' => $money, 'before' => $mod->old_price, 'after' => $mod->old_price + $money, 'type' => 6, 'memo' => '提现退回', 'is_old' => 1]);
                    $mod->old_price += $money;
                } elseif ($with_type == 2) {

                    AdvertPriceLog::create(['user_id' => $mod->user_id, 'money' => abs($money), 'before' => $mod->advert_price, 'after' => $mod->advert_price + $money, 'type' => 3, 'memo' => '提现退回']);
                    $mod->advert_price += $money;
                } elseif ($with_type == 3) {

                    MoneyLog::create(['user_id' => $mod->user_id, 'money' => $money, 'before' => $mod->lp_price, 'after' => $mod->lp_price + $money, 'type' => 6, 'memo' => '提现退回', 'is_old' => 2]);
                    $mod->lp_price += $money;
                }else {

                    MoneyLog::create(['user_id' => $mod->user_id, 'money' => $money, 'before' => $mod->price, 'after' => $mod->price + $money, 'type' => 6, 'memo' => '提现退回']);
                    $mod->price += $money;
                }

            }
        } else {
            //提现成功写入日志
            //MoneyLog::create(['user_id' => $mod->user_id, 'money' => $money, 'before' => $mod->price + $money, 'after' => $mod->price, 'type' => 6, 'memo' => '提现成功']);
        }
        $mod->save();
    }

    /**
     * [recharge 充值]
     * @param ShareUser $mod [description]
     * @param  [type]     $money  [description]
     * @param boolean $return [余额是否要返回]
     * @return [type]             [description]
     * @since  2022-09-30
     */
    public function recharge($order, $money)
    {
        if (!$mod = $this->where(['user_id' => $order->user_id])->find()) {
            return;
        }
        if (MoneyLog::where(['user_id' => $order->user_id, 'type' => 8, 'order_sn' => $order->order_sn])->find()) {
            return;
        }
        $mod->price += $money;
        //提现成功写入日志
        MoneyLog::create(['user_id' => $mod->user_id, 'money' => $money, 'before' => $mod->price - $money, 'after' => $mod->price, 'type' => 8, 'memo' => '用户充值成功', 'order_sn' => $order->order_sn]);

        $mod->save();
    }

    /**
     * [ordersRefundFinish 订单退货返还]
     * @param  [type]     $order      [app\admin\model\shopro\order\Order]
     * @param  [type]     $refund_money [description]
     * @return [type]                   [description]
     * @since  2022-10-11
     */
    public function ordersRefundFinish($order, $refund_money)
    {
        $mod = ShareUser::where(['is_delete' => 0, 'user_id' => $order->user_id])->find();
        if (!$mod) {
            return;
        }

        $money_log = \db("user_money_log")->where('type', 2)
            ->where('memo', 'like', $order->order_sn)->find();
        if ($money_log) {
            \db("log_error")->insert([
                'content' => $order->order_sn . '系统异常，一次退回余额', 'system err,money log',
                'addtime' => time(),
            ]);
            return;
        }
        if($order->mutual_amount > 0 ){
            $old_mutual_money = $mod->mutual_money;
            $param = [
                "user_id" => $order->user_id,
                "wallet" => $order->mutual_amount,       // 符号直接存到记录里面
                "before" => $old_mutual_money,
                "after" => $old_mutual_money + $order->mutual_amount,
                "type" => 'mutual_add',
                "memo" => '互助金增加',
                "item_id" => 0,
                "wallet_type" => 'mutual',
                "ext" => [],
                "oper_type" => 'system',
                "oper_id" => 0,
                "createtime" => time()
            ];
            $save1 = Db::name('shopro_user_wallet_log')->insert($param);
            self::where(['is_delete' => 0, 'user_id' => $order->user_id])->setInc('mutual_money', $order->mutual_amount);
            $refund_money = $refund_money - $order->mutual_amount;
        }
        if($refund_money > 0){
            if($order->is_old == 1){
                //
                MoneyLog::create(['user_id' => $order->user_id, 'money' => $refund_money, 'before' => $mod->old_price, 'after' => $mod->old_price + $refund_money, 'type' => 2, 'memo' => '订单号：' . $order->order_sn . '订单退货成功','order_sn' => $order->order_sn ,'is_old'=>1]);

                self::where(['is_delete' => 0, 'user_id' => $order->user_id])->setInc('old_price', $refund_money);

            }elseif($order->is_old == 2){
                //
                MoneyLog::create(['user_id' => $order->user_id, 'money' => $refund_money, 'before' => $mod->lp_price, 'after' => $mod->lp_price + $refund_money, 'type' => 2, 'memo' => '订单号：' . $order->order_sn . '订单退货成功','order_sn' => $order->order_sn ,'is_old'=>2 ]);

                self::where(['is_delete' => 0, 'user_id' => $order->user_id])->setInc('lp_price', $refund_money);
            }elseif($order->is_old == 3){
                //
                $after =  $mod->advert_price + $refund_money;
                AdvertPriceLog::create(['user_id' =>  $order->user_id, 'money' => $refund_money, 'before' => $mod->advert_price, 'after' => $after, 'memo' =>  '订单号：' . $order->order_sn . '订单退货成功',]);
               // MoneyLog::create(['user_id' => $order->user_id, 'money' => $refund_money, 'before' => $mod->advert_price, 'after' => $mod->advert_price + $refund_money, 'type' => 2, 'memo' => '订单号：' . $order->order_sn . '订单退货成功','order_sn' => $order->order_sn ,'is_old'=>3 ]);

                self::where(['is_delete' => 0, 'user_id' => $order->user_id])->setInc('advert_price', $refund_money);
            }else{
                MoneyLog::create(['user_id' => $order->user_id, 'money' => $refund_money, 'before' => $mod->price, 'after' => $mod->price + $refund_money, 'type' => 2, 'memo' => '订单号：' . $order->order_sn . '订单退货成功','order_sn' => $order->order_sn ]);

                self::where(['is_delete' => 0, 'user_id' => $order->user_id])->setInc('price', $refund_money);
            }
        }


    }

    /**
     * [ordersPay 订单支付]
     * @param  [type]     $order      [app\admin\model\shopro\order\Order]
     * @param  [type]     $refund_money [description]
     * @return [type]                   [description]
     * @since  2022-10-11
     */
    public function ordersPay($order, $money, $is_old = 0)
    {

        $mod = ShareUser::where(['is_delete' => 0, 'user_id' => $order->user_id])->find();
        if ($is_old == 1) {
            if (!$mod || $mod->old_price - $money < 0) {
                $re_data['status'] = 1;
                $re_data['mgs'] = "可用余额不足";
                return $re_data;
               // new Exception('可用余额不足');
            }
        }elseif ($is_old == 2){
            //file_put_contents('ttorder.txt',$mod->lp_price - $money."_".$money."_".$is_old);
            if (!$mod || $mod->lp_price - $money < 0) {
                $re_data['status'] = 1;
                $re_data['mgs'] = "可用余额不足";
                return $re_data;
               // new Exception('可用余额不足');
            }
        } elseif ($is_old == 3){
           // file_put_contents('ttorder.txt',$mod->lp_price - $money."_".$money."_".$is_old);
            if (!$mod || $mod->advert_price - $money < 0) {
                $re_data['status'] = 1;
                $re_data['mgs'] = "可用余额不足";
                return $re_data;
                // new Exception('可用余额不足');
            }
        }else {
            if (!$mod || $mod->price - $money < 0) {
                $re_data['status'] = 1;
                $re_data['mgs'] = "可用余额不足";
                return $re_data;
               // new Exception('可用余额不足');
            }
        }

        // if ($mod->price - $money <0 ) {
        //     new Exception('可用余额不足');
        // }
        //提现成功写入日志
        //MoneyLog::create(['user_id' => $order->user_id, 'money' => $money, 'before' => $mod->price, 'after' => $mod->price - $money, 'type' => 2, 'memo' => '订单号：' . $order->order_sn . '订单支付成功', 'is_old' => $is_old]);

        if ($is_old == 1) {
            MoneyLog::create(['user_id' => $order->user_id, 'money' => $money, 'before' => $mod->old_price, 'after' => $mod->old_price - $money, 'type' => 2, 'memo' => '订单号：' . $order->order_sn . '订单支付成功', 'is_old' => $is_old,'order_id'=>$order->id]);

            self::where(['is_delete' => 0, 'user_id' => $order->user_id])->setDec('old_price', $money);
        }elseif ($is_old == 2){
            MoneyLog::create(['user_id' => $order->user_id, 'money' => $money, 'before' => $mod->lp_price, 'after' => $mod->lp_price - $money, 'type' => 2, 'memo' => '订单号：' . $order->order_sn . '订单支付成功', 'is_old' => $is_old,'order_id'=>$order->id]);
            self::where(['is_delete' => 0, 'user_id' => $order->user_id])->setDec('lp_price', $money);
        }elseif ($is_old == 3){
            $after =  $mod->advert_price - $money;
            AdvertPriceLog::create(['user_id' =>  $order->user_id, 'money' => $money, 'before' => $mod->advert_price, 'after' => $after,'order_id'=>$order->id, 'memo' => '订单号：' . $order->order_sn . '订单支付成功']);
           // MoneyLog::create(['user_id' => $order->user_id, 'money' => $money, 'before' => $mod->advert_price, 'after' => $mod->advert_price - $money, 'type' => 2, 'memo' => '订单号：' . $order->order_sn . '订单支付成功', 'is_old' => $is_old]);
            self::where(['is_delete' => 0, 'user_id' => $order->user_id])->setDec('advert_price', $money);
        } else {
            MoneyLog::create(['user_id' => $order->user_id, 'money' => $money, 'before' => $mod->price, 'after' => $mod->price - $money, 'type' => 2, 'memo' => '订单号：' . $order->order_sn . '订单支付成功', 'is_old' => $is_old,'order_id'=>$order->id]);
            self::where(['is_delete' => 0, 'user_id' => $order->user_id])->setDec('price', $money);
        }
        $re_data['status'] = 0;
        $re_data['mgs'] = "";
        return $re_data;

    }

    /**
     * [oldOrdersRefundFinish 订单退货返还]
     * @param  [type]     $order      [app\admin\model\shopro\order\Order]
     * @param  [type]     $refund_money [description]
     * @return [type]                   [description]
     * @since  2022-10-11
     */
    public function oldOrdersRefundFinish(\app\admin\model\old\order\Aftersale $order, $refund_money)
    {
        $mod = ShareUser::where(['is_delete' => 0, 'user_id' => $order->user_id])->find();
        if (!$mod) {
            return;
        }
        //提现成功写入日志
        MoneyLog::create(['user_id' => $order->user_id, 'money' => $refund_money, 'before' => $mod->price, 'after' => $mod->price + $refund_money, 'type' => 2, 'memo' => '旧订单号：' . $order->aftersale_sn . '订单退货成功','order_sn' => $order->aftersale_sn]);

        self::where(['is_delete' => 0, 'user_id' => $order->user_id])->setInc('price', $refund_money);
    }


    public function getTeamUser($userId)
    {
        $teamUidArr = [];
        $noteamUidArr = [];
        $info = $this->db('share_user')->where(['user_id' => $userId])->find();
        if (empty($info)) {
            return ['team_user' => $teamUidArr, 'noteam_user' => $noteamUidArr];
        }

        $puserlist = $this->db('share_user')->where(['role_url' => ['like', "%/" . $userId . $info['role_url'] . "%"]])->order('id DESC')->select();
        //echo Db::table('share_user')->getLastSql();die;
        if (!empty($puserlist)) {
            $userIdsStr = '';
            foreach ($puserlist as $vv) {
                $userIdsStr = $userIdsStr . '/' . $vv['user_id'] . $vv['role_url'];
            }

            $userArray = explode('/', $userIdsStr);
            $teamArray = array_filter($userArray);
            $teamArray = array_unique($teamArray);
            rsort($teamArray);
            foreach ($teamArray as $k => $uid) {
                if ($uid >= $userId) {
                    $teamUidArr[$k] = $uid;
                } else {
                    $noteamUidArr[$k] = $uid;
                }
            }
        } else {
            $teamUidArr[] = $userId;
            $noteamUidArr = array_unique(array_filter(explode('/', $info['role_url'])));
        }
        return ['team_user' => $teamUidArr, 'noteam_user' => $noteamUidArr];
    }

    public function getTeamUser_1($userId)
    {
        $teamUidArr = [];
        $noteamUidArr = [];
        $info = $this->db('share_user')->where(['user_id' => $userId])->find();
        if (empty($info)) {
            return ['team_user' => $teamUidArr, 'noteam_user' => $noteamUidArr];
        }

        $puserlist = $this->db('share_user')->where(['role_url' => ['like', "%/" . $userId . $info['role_url']]])->order('id DESC')->select();
        //echo Db::table('share_user')->getLastSql();die;
        if (!empty($puserlist)) {
            $userIdsStr = '';
            foreach ($puserlist as $vv) {
                $str = str_replace("/" . $userId . $info['role_url'], '', $vv['role_url']);
                $userIdsStr = $userIdsStr . '/' . $vv['user_id'] . $str;
            }

            $userArray = explode('/', $userIdsStr);
            $teamArray = array_filter($userArray);
            $teamArray = array_unique($teamArray);
            rsort($teamArray);
            foreach ($teamArray as $k => $uid) {
                $teamUidArr[$k] = $uid;
            }
        } else {
            $teamUidArr[] = $userId;
        }

        $noteamUidArr = array_unique(array_filter(explode('/', $info['role_url'])));
        return ['team_user' => $teamUidArr, 'noteam_user' => $noteamUidArr];
    }

    /**
     * 切网体 老网体上级人员移除、新网体人员加入
     * @param $userId
     * @param $newUserId
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function setTeamUser($userId, $newUserId)
    {
        $userInfo = $this->db('share_user')->where(['user_id' => $userId])->find();
        if ($userInfo) {
            $list = \db("share_user")
                ->where('user_id', 'in', explode('/', $userInfo['role_url']))
                ->select();

            $items = array_merge([$userId], array_column($list, 'user_id'));
            foreach ($items as $v) {
                $count = \db("share_user")->where('role_url', 'like', '%/' . $v . '/%')
                    ->count();
                \think\Log::error([$v, $count + 1]);
                \db('share_user')->where(['user_id' => $v])->update([
                    'amount' => $count + 1,
                ]);
            }
        }

        $newUserInfo = $this->db('share_user')->where(['user_id' => $newUserId])->find();
        if ($newUserInfo) {
            $list = \db("share_user")
                ->where('user_id', 'in', explode('/', $newUserInfo['role_url']))
                ->select();

            $items = array_merge([$newUserId], array_column($list, 'user_id'));
            foreach ($items as $v) {
                $count = \db("share_user")->where('role_url', 'like', '%/' . $v . '/%')->count();
                \think\Log::error([$v, $count + 1]);
                \db('share_user')->where(['user_id' => $v])->update([
                    'amount' => $count + 1,
                ]);
            }
        }
    }

    /**
     * @param $mobile
     * @param $score
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 通过手机号加积分
     */
    public static function userScoreChange($mobile, $score)
    {
        if (!$mobile || !$score) {
            $re_data['status'] = 0;
            $re_data['msg'] = "缺少参数";
            return $re_data;
        }
        if ($score == 0) {
            $re_data['status'] = 0;
            $re_data['msg'] = "变动积分不能为0";
            return $re_data;
        }
        $user_data = Db::name("user")->where(['mobile' => $mobile])->find();
        if (empty($user_data)) {
            $re_data['status'] = 0;
            $re_data['msg'] = "手机号不存在";
            return $re_data;
        }
        $subgift_user = (new ShareUser())->get(['user_id' => $user_data['id']]);
        $before = $subgift_user->score;
        $after = $subgift_user->score + $score;
        $subgift_user->score = $after;
        $subgift_user->save();
        ScoreLog::create(['user_id' => $user_data['id'], 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => "积分变动", 'type' => 1, 'mobile' => $mobile]);
        $re_data['status'] = 1;
        $re_data['msg'] = "";
        return $re_data;
    }

    /**
     * @param $user_id
     * @param $price
     * @param $type
     * @param $memo
     * @param $db
     * @param $ext
     * @return bool|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 资金变动
     */
    public function userPriceLog($user_id, $price, $type, $memo = '', $db = false, $ext = [])
    {
        if (!$db) {
            Db::startTrans();
        }
        $share_user = (new ShareUser())->where(['user_id' => $user_id])->find();
        if (!$share_user) {
            Db::rollback();
            $re_data['status'] = 0;
            $re_data['msg'] = "未找到用户";
            return $re_data;
        }
        // 判断金额
        if ($price == 0) {
            Db::rollback();
            $re_data['status'] = 0;
            $re_data['msg'] = "请输入正确的金额";
            return $re_data;
        }

        $is_old = 0;
        $mobile = '';
        if(isset($ext['is_old'])){
            $is_old = $ext['is_old'];
        }
        if(isset($ext['mobile'])){
            $mobile = $ext['mobile'];
        }
        if ($price < 0) {
            if($is_old == 1){
                if ($share_user['old_price'] < abs($price)) {//取绝对值
                    Db::rollback();
                    $re_data['status'] = 0;
                    $re_data['msg'] = "可用余额不足";
                    return $re_data;
                }
            }elseif ($is_old == 2){
                if ($share_user['lp_price'] < abs($price)) {//取绝对值
                    Db::rollback();
                    $re_data['status'] = 0;
                    $re_data['msg'] = "可用余额不足";
                    return $re_data;
                }
            }else{
                if ($share_user['price'] < abs($price)) {//取绝对值
                    Db::rollback();
                    $re_data['status'] = 0;
                    $re_data['msg'] = "可用余额不足";
                    return $re_data;
                }
            }

        }
        if($is_old == 1){
            $before = $share_user['old_price'];
            $after = $share_user['old_price'] + $price;
            $up_user['old_price'] = $after;
        }elseif ($is_old == 2){
            $before = $share_user['lp_price'];
            $after = $share_user['lp_price'] + $price;
            $up_user['lp_price'] = $after;
        }elseif ($is_old == 0){
            $before = $share_user['price'];
            $after = $share_user['price'] + $price;
            $up_user['price'] = $after;
        }

        $cre_log = MoneyLog::create(['user_id' => $user_id, 'money' => abs($price), 'before' => $before, 'after' => $after, 'type' => $type, 'memo' => $memo,'is_old'=>$is_old,'mobile'=>$mobile]);
        $save_share = (new ShareUser())->where(['user_id' => $user_id])->update($up_user);
        if ($save_share && $cre_log) {
            if (!$db) {
                Db::commit();
            }
            $re_data['status'] = 1;
            $re_data['msg'] = "成功";
            return $re_data;
        } else {
            Db::rollback();
            $re_data['status'] = 0;
            $re_data['msg'] = "金额更新失败";
            return $re_data;
        }
    }

    /**
     * @param $user_id
     * @param $stock
     * @param $type
     * @param $memo
     * @param $db
     * @param $ext
     * @return bool|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 资金变动
     * qi10.28
     */
    public function userStockLog($user_id, $stock, $type, $memo = '', $db = false, $ext = [])
    {
        if (!$db) {
            Db::startTrans();
        }
        $share_user = (new ShareUser())->where(['user_id' => $user_id])->find();
        if (!$share_user) {
            Db::rollback();
            $re_data['status'] = 0;
            $re_data['msg'] = "未找到用户";
            return $re_data;
        }
        // 判断金额
        if ($stock == 0) {
            Db::rollback();
            $re_data['status'] = 0;
            $re_data['msg'] = "请输入正确的股票值";
            return $re_data;
        }
        if ($stock < 0) {
            if ($share_user['stock'] < abs($stock)) {//取绝对值
                Db::rollback();
                $re_data['status'] = 0;
                $re_data['msg'] = "可用股票值不足";
                return $re_data;
            }
        }
        $after = $share_user['stock'] + $stock;
        $up_user['stock'] = $after;
        $save_share = (new ShareUser())->where(['user_id' => $user_id])->update($up_user);
        $cre_log = StockLog::create(['user_id' => $user_id, 'stock' => abs($stock), 'before' => $share_user['stock'], 'after' => $after, 'type' => $type, 'memo' => $memo]);
        if ($save_share && $cre_log) {
            if (!$db) {
                Db::commit();
            }
            $re_data['status'] = 1;
            $re_data['msg'] = "成功";
            return $re_data;
        } else {
            Db::rollback();
            $re_data['status'] = 0;
            $re_data['msg'] = "股票值更新失败";
            return $re_data;
        }
    }

    /**
     * @param $user_id
     * @param $stock
     * @param $type
     * @param $memo
     * @param $db
     * @param $ext
     * @return bool|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 资金变动
     * qi10.28
     */
    public function userScoreLog($user_id, $score, $type, $memo = '', $db = false, $ext = [])
    {
        if (!$db) {
            Db::startTrans();
        }
        $share_user = (new ShareUser())->where(['user_id' => $user_id])->find();
        if (!$share_user) {
            Db::rollback();
            $re_data['status'] = 0;
            $re_data['msg'] = "未找到用户";
            return $re_data;
        }
        // 判断金额
        if ($score == 0) {
            Db::rollback();
            $re_data['status'] = 0;
            $re_data['msg'] = "请输入正确的积分";
            return $re_data;
        }
        if ($score < 0) {
            if ($share_user['score'] < abs($score)) {//取绝对值
                Db::rollback();
                $re_data['status'] = 0;
                $re_data['msg'] = "可用积分不足";
                return $re_data;
            }
        }
        $mobile = '';
        if(isset($ext['mobile'])){
            $mobile = $ext['mobile'];
        }
        $after = $share_user['score'] + $score;
        $up_user['score'] = $after;
        $save_share = (new ShareUser())->where(['user_id' => $user_id])->update($up_user);
        $cre_log = ScoreLog::create(['user_id' => $user_id, 'score' => abs($score), 'before' => $share_user['score'], 'after' => $after, 'type' => $type, 'memo' => $memo,'mobile'=>$mobile]);
        if ($save_share && $cre_log) {
            if (!$db) {
                Db::commit();
            }
            $re_data['status'] = 1;
            $re_data['msg'] = "成功";
            return $re_data;
        } else {
            Db::rollback();
            $re_data['status'] = 0;
            $re_data['msg'] = "积分更新失败";
            return $re_data;
        }
    }

    /**
     * @param $pids
     * @param $sum
     * @return int|mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     *  //齐10。31
     */
    public function re_user_sum($pids, $sum)
    {
        $where['parent_id'] = ['in', $pids];
        $ut_data = Db::name('share_user')->where($where)->field("user_id")->select();
        $pids = array_column($ut_data, 'user_id');
        if (count($pids) > 0) {
            $sum += 1;
            $where['parent_id'] = ['in', $pids];
            $ut_data = Db::name('share_user')->where($where)->field("user_id")->select();
            $pids = array_column($ut_data, 'user_id');
            if (count($pids) > 0) {
                $sum += 1;
                $where['parent_id'] = ['in', $pids];
                $ut_data = Db::name('share_user')->where($where)->field("user_id")->select();
                $pids = array_column($ut_data, 'user_id');
                if (count($pids) > 0) {
                    $sum += 1;
                    $where['parent_id'] = ['in', $pids];
                    $ut_data = Db::name('share_user')->where($where)->field("user_id")->select();
                    $pids = array_column($ut_data, 'user_id');
                    if (count($pids) > 0) {
                        return $sum;
                    } else {
                        return $sum;
                    }
                } else {
                    return $sum;
                }
            } else {
                return $sum;
            }
        } else {
            return $sum;
        }
        return $sum;
    }

    public function check_share($num = 1)
    {
        //第一步 校验路径
        $this->role_url($num);

        //校验所属团队
        $this->up_share($num);

        //校验团队人数
        $this->up_share2($num);

        //校验团队级别
        $this->role_level($num);

        //校验独立分割
        $this->check_flags($num);
    }

    protected function check_flags($num = 1)
    {
        $where['user_id'] = ['>', $num];
        $u_data = Db::name("share_user")->where($where)->order('id desc')->select();
        foreach ($u_data as $k => $v) {
            $flags = $this->get_flags($v['parent_id']);
            echo $k . PHP_EOL;
            if ($flags) {
                $user = \db('share_user')->where('user_id', $v['user_id'])->find();
                if (empty($user)) {
                    echo $v['user_id'] . PHP_EOL;
                    \db("share_user_flags")->insert([
                        'user_id' => $v['user_id'],
                        'user_flags' => $v['user_flags'],
                        'addtime' => time(),
                    ]);
                }
            }
        }
    }

    private function get_flags($user_id)
    {
        $flags = \db('share_user')->where('user_id', $user_id)->field('parent_id,user_flags')->find();
        if ($flags['parent_id'] < 10000) {
            return '';
        }
        if (empty($flags)) {
            return $this->get_flags($flags['parent_id']);
        }

        return $flags['user_flags'];
    }

    /**
     * @return void
     * 校验团队级别
     */
    public function role_level($num = 1)
    {
        $where['user_id'] = ['>', $num];
        $list = (new ShareUser())->where($where)->select();
        foreach ($list as $v) {

            $role1 = 0;
            $role2 = 0;
            $role3 = 0;

            $arr = \db("share_user")->where(['parent_id' => $v['user_id']])->select();
            foreach ($arr as $vv) {
                if ($vv['role_type'] == 1) {
                    $role1 = $this->get_role($vv['user_id'], $vv['role_url'], $vv['role']);
                } else if ($vv['role_type'] == 2) {
                    $role2 = $this->get_role($vv['user_id'], $vv['role_url'], $vv['role']);
                } else if ($vv['role_type'] == 3) {
                    $role3 = $this->get_role($vv['user_id'], $vv['role_url'], $vv['role']);
                }
            }

            echo $v['user_id'] . ":" . $role1 . ":" . $role2 . ":" . $role3 . PHP_EOL;
            \db("share_user")->where('id', $v['id'])->update([
                'role1' => $role1,
                'role2' => $role2,
                'role3' => $role3,
            ]);

            $role0 = 0;
            if ($role1 <= $role2) {
                $role0 = $role1;
            } else {
                $role0 = $role2;
            }

            if ($role0 > $role3) {
                $role0 = $role3;
            }

            $arr = [
                1 => 1,
                2 => 3,
                3 => 12,
                4 => 100,
                5 => 500,
                6 => 3000,
                7 => 20000,
            ];

            if ($role0 + 1 < 8 && $role0 + 1 > $v['role'] && $v['amount'] >= $arr[$role0 + 1]) {
                \db("share_user")->where('id', $v['id'])->update([
                    'role' => $role0 + 1,
                ]);
            }
        }
    }

    protected function get_role($user_id, $role_url, $role)
    {

        $role_url = '/' . $user_id . $role_url;
        $items = \db("share_user")->where('role_url', 'like', '%' . $role_url . '%')
            ->field('role_url,user_id')->select();

        $item_arr = array_column($items, 'role_url');
        $urls = array_column($items, 'user_id');
        array_push($urls, $user_id);
        foreach ($item_arr as $kv) {
            $kkv = str_replace($role_url, '/', $kv);
            $urls = array_merge($urls, explode('/', $kkv));
            $urls = array_unique($urls);
        }

        $roles = \db("share_user")->where('user_id', 'in', $urls)->field('role')
            ->order('role desc')->select();
        return count($roles) > 0 ? $roles[0]['role'] : 0;
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 现有网体里面赋值所在团队
     */
    public function up_share($num = 1)
    {
        $where['user_id'] = ['>', $num];
        $u_data = Db::name("share_user")->where($where)->select();

        foreach ($u_data as $k => $v) {
            $temp_data = Db::name("share_user")->where(['parent_id' => $v['user_id']])->select();
            if (count($temp_data) > 3) {
                $str = '节点有误' . $v['user_id'] . PHP_EOL;
                db('log_error')->insert([
                    'content' => $str,
                    'addtime' => time(),
                ]);
            }

            foreach ($temp_data as $key => $value) {
                Db::name("share_user")->where(['id' => $value['id']])
                    ->update(['role_type' => $key + 1]);
            }
        }

        echo "成功";
    }

    /**
     * @param $num
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws PDOException
     * @throws \think\Exception
     * 校验团队人数
     */
    protected function up_share2($num = 1)
    {
        $where['user_id'] = ['>', $num];
        $u_data = Db::name("share_user")->where($where)->order('id desc')->select();

        foreach ($u_data as $k => &$v) {
            $user = (new ShareUser())->get(['user_id' => $v['user_id']]); // 分销用户
            $user->amount = 0;
            $user->save();
        }

        foreach ($u_data as $k => $v) {
            echo $v['user_id'] . PHP_EOL;
            $url = '/' . $v['user_id'] . $v['role_url'];
            $count = \db("share_user")->where('role_url', 'like', '%' . $url . '%')->count();
            \db("share_user")->where('id', $v['id'])->update(['amount' => $count + 1]);
        }
    }

    /**
     * 校验团队路径
     */
    protected function role_url($num = 1)
    {
        $where['user_id'] = ['>', $num];
        $list = (new ShareUser())->where($where)->select();
        foreach ($list as $v) {
            $role_url = (new ShareUser())->add_promotion($v['user_id'], '');
            echo $v['user_id'] . PHP_EOL;
            \db("share_user")->where('id', $v['id'])->update(['role_url' => str_replace('/' . $v['user_id'], '', $role_url)]);
        }
    }

    public function del_test_user($flag = 0)
    {
        $where["share_retreat"] = 0;
        $where["o.status"] = 1;
        $today_0 = strtotime(date("Y-m-d", time()));
        $before_two_hour = time() - 3 * 60 * 60;
//        $before_two_hour=time()-60;

        if ($flag == 0) {
            $where['paytime'] = ['<', $before_two_hour];
        }
        $two_hours_orders = \addons\shopro\model\Order::alias("o")
            ->join("shopro_order_item t", "t.order_id=o.id", 'LEFT')
            ->join("user u", "u.id=o.user_id", 'LEFT')
            ->where($where)
            ->where("pay_fee", '>', 0)
            ->where("u.staff", 2)
            ->field("o.*,t.order_id,t.id as order_item_id,u.staff")
            ->select();

        if (!empty($two_hours_orders)) {
            foreach ($two_hours_orders as $k => $v) {
                //删除收益
                (new ShareMoney())->where(['order_id' => $v['id']])->delete();
                (new ShareReward())->where(['order_id' => $v['id']])->delete();
                //删除分账
                Db::name("shopro_order_bill")->where(['order_sn'=>$v['order_sn']])->delete();

                $params["user_id"] = $v["user_id"];
                $params["refund_fee"] = $v["total_fee"];
                $params["order_id"] = $v["id"];
                $params["order_item_id"] = $v["order_item_id"];
                $params["content"] = "超过两小时，自动退货";
                $res11 = \addons\shopro\model\OrderAftersale::aftersale_two_hour($params);
            }
        }

        $where1 = [];
        $before_three_hour = time() - 6 * 60 * 60;
        if ($flag == 0) {
            $where1['createtime'] = ['<', $before_three_hour];
        }

        $staff_2_users = \app\common\model\User::where('staff', 2)
            ->where($where1)
            ->order("id desc")
            ->select();

        if (!empty($staff_2_users)) {
            foreach ($staff_2_users as $k => $v) {
                echo "del:" . $v['id'] . PHP_EOL;
                $share_data = Db::name("share_user")->where('user_id', $v["id"])->find();
                $user_data = Db::name("user")->where(['id'=>$share_data['parent_id']])->find();

                Db::name("user_id_card")->where('user_id', $v["id"])->delete();
                Db::name("share_user")->where('user_id', $v["id"])->delete();
                Db::name("user_money_log")->where('user_id', $v["id"])->delete();
                Db::name("user_withdraw")->where('user_id', $v["id"])->delete();
                Db::name("shopro_order")->where('user_id', $v["id"])->delete();
                Db::name("user")->where("staff", 2)->where('id', $v["id"])->delete();
                $sum_pay_fee = Db::name("shopro_order")->where('status','>',0)->where(['share_retreat'=>0])->sum("pay_fee");
                $this->achievement_dow($share_data['parent_id'],$sum_pay_fee);
                //删除好友关系
                (new CommonShare())->delUserf($v["id"]);
                //qi11.11

                if(isset($share_data) && $share_data['role'] > 0 && $user_data['staff'] != 2){
                    $this->promotion_dow($share_data['parent_id'], $share_data['role_type'],1,$share_data['user_id']);
                }
            }
        }
    }
    public function achievement_dow($user_id,$order_fee){
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) {
            return 0;
        }
        $user->achievement = bcsub($user['achievement'],$order_fee,2);
        $user->save();
        return $this->achievement_dow($user->parent_id, $order_fee);
        if($user_id == 1){
            return 0;
        }
    }
    public function setSepTeamUser($userId)
    {
        $user = \db("share_user")->where('user_id', $userId)->find();
        if (empty($user)) {
            return ['code' => 0, 'msg' => '未找到用户'];
        }

        if ($user['role'] < 1) {
            return ['code' => 0, 'msg' => '推广员以下用户不可设置分隔收益'];
        }

        $user_flags = '';
        $user_flags_1 = Db::name('share_user_flags')->where('user_id', $userId)->find();
        if (empty($user['user_flags'])) {
            $user_flags = \app\common\model\User::user_flags();
            \db("share_user")->where('user_id', $userId)->update([
                'user_flags' => $user_flags,
                'is_sep_income' => 1,
            ]);
        } else {
            $user_flags = $user['user_flags'];
            if ($user_flags_1['user_flags'] == $user['user_flags']) {
                return ['code' => 1, 'msg' => '已分割，无需分割'];
            }
        }

        if ($user_flags_1) {
            //如果存在 剥离老的网体，重新设置新的独立分割
            $list = \db("share_user")->where('role_url', 'like', '%/' . $userId . '/%')
                ->field("user_id")->select();
            \db('share_user_flags')
                ->where('user_id', 'in', array_merge([$userId], array_column($list, 'user_id')))
                ->delete();
        }

        $puserlist = Db::table('share_user')->where(['role_url' =>
            ['like', '%/' . $userId . '/%']])
            ->order('id DESC')->select();

        $arr = [[
            'user_id' => $userId,
            'user_flags' => $user_flags,
            'addtime' => time()
        ]];

        foreach ($puserlist as $vv) {
            $info = \db('share_user_flags')->where('user_id', $vv['user_id'])->find();
            if (!$info) {
                array_push($arr, [
                    'user_id' => $vv['user_id'],
                    'user_flags' => $user_flags,
                    'addtime' => time()
                ]);
            }
        }

        if (count($arr) > 0) {
            Db::name("share_user_flags")->insertAll($arr);
        }
        return ['code' => 1, 'msg' => '完成'];
    }

    /**
     * 统计团队数据
     */
    public function teamCount($user_id, $is_leader = 2)
    {
        $top_id = \db("user")->where('mobile', '13131388888')->value('id');
        if ($user_id == $top_id || $is_leader == 1) {//统计全部数据
            $s = '%/' . 1;
        } else {
            $s = '%/' . $user_id . '/%';
        }
        $sh_user = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0])->select();
        $user_id_arr = array_column($sh_user, 'user_id');
        $user_id_arr = array_merge($user_id_arr, [$user_id]);
        //$arr_count = (new ShareUser())->where('user_id', 'in', $user_id_arr)->select();
        $user_sum = (new ShareUser())->where('user_id', 'in', $user_id_arr)->count();
        $user_score = (new ShareUser())->where('user_id', 'in', $user_id_arr)->sum('score');
        $user_price = (new ShareUser())->where('user_id', 'in', $user_id_arr)->sum('price');
        $user_roles = (new ShareUser())->where('user_id', 'in', $user_id_arr)->group('role')->order("role desc")->select();
        $re_list = [];
        if ($user_roles) {
            $pattern = Db::name("config")->where(['name'=>'pattern'])->value('value');
            if(isset($pattern) && $pattern == 2){
                $dj = ['无', '代言人', '创客', '网店店长', '网店店主', '一级经销商', '二级经销商', '三级经销商'];
            }elseif(isset($pattern) && $pattern == 3){
                $dj = ['无', '推广员', '代言人', '一星网店', '二星网店', '一级代理商', '二级代理商', '三级代理商'];
            }else{
                $dj = ['无', '推广员', '代言人', '一星网店经销商', '二星网店经销商', '银牌经销商', '金牌经销商', '钻石经销商'];
            }
            foreach ($user_roles as $k => $v) {
                $re_list[] = [
                    "role_name" => $dj[$v["role"]],
                    "user_sum" => (new ShareUser())->where('user_id', 'in', $user_id_arr)->where(['role' => $v['role']])->count(),
                    "user_score" => sprintf("%.2f", (new ShareUser())->where('user_id', 'in', $user_id_arr)->where(['role' => $v['role']])->sum('score')),
                    "user_price" => sprintf("%.2f", (new ShareUser())->where('user_id', 'in', $user_id_arr)->where(['role' => $v['role']])->sum('price')),
                ];
            }
        }
        $re['user_sum'] = $user_sum;
        $re['user_score'] = sprintf("%.2f", $user_score);
        $re['user_price'] = sprintf("%.2f", $user_price);
        $re['re_list'] = $re_list;
        return $re;
    }

    /**
     * 总分享人数
     */
    public function teamUserCount($user_id)
    {
        $flags = Db::name("share_user_flags")->where(['user_id' => $user_id])->find();


        $arr_count = [];
        if ($flags) {//是分割用户
            $share = Db::name("share_user")->where(['user_flags' => $flags['user_flags']])->find();
            $arr_count = (new ShareUser())->where('role_url', 'like', '%/' . $share['user_id'] . '/%')
                ->whereOr(['user_id' => $share['user_id']])
                ->where('role > 0')
                ->count();

        } else {//不是分割用户
            $flags_liser = Db::name("share_user_flags")->select();
            $user_id_arr = array_column($flags_liser, 'user_id');
            $arr_count = (new ShareUser())->where('user_id', 'not in', $user_id_arr)->where('role > 0')->count();
        }

        //找头部账号
        $top_id = \db("user")->where('mobile', '13131388888')->value('id');
        if ($user_id == $top_id) {
            $arr_count = (new ShareUser())->where('role_url', 'like', '%/' . $top_id)
                ->where('role > 0')
                ->count();
            $arr_count++;
        }

        $top = \db("share_user")->where('user_id', $user_id)->where('is_leader', 1)->find();
        if ($top) {
            $arr_count = (new ShareUser())->where('role_url', 'like', '%/' . $top_id)
                ->where(['is_delete' => 0])
                ->where('role > 0')
                ->count();
            $arr_count++;
        }

        return $arr_count;
    }
    //我的总分享人数
    public function myTeamUserCount($user_id)
    {
        $arr_count = (new ShareUser())->where('role_url', 'like', '%/' .$user_id . '/%')
            ->whereOr(['user_id' => $user_id])
            ->where('role > 0')
            ->count();

        //找头部账号
        $top_id = \db("user")->where('mobile', '13131388888')->value('id');
        if ($user_id == $top_id) {
            $arr_count = (new ShareUser())->where('role_url', 'like', '%/' . $top_id)
                ->where('role > 0')
                ->count();
            $arr_count++;
        }
        return $arr_count;
    }
    // 上级用户降级//qi11.11
    public function promotion_dow($user_id, $role_type, $is_dow=0,$low_user_id)
    {
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) {
            return 0;
        }
        if($user_id == 1){
            $s = '%/' . 1;
        }else{
            $s = '%/' . $user_id . '/%';
        }
        $sonShareCount = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0])
            ->where('role > 0')
            ->count();
        $user->amount = $sonShareCount+1;
        $user->save();
        if($is_dow == 0){
            return $this->promotion_dow($user->parent_id, $user->role_type,$is_dow,$low_user_id);
        }

        //手动设置的级别，不做降级
        if($user->manual_role==1){
            return $this->promotion_dow($user->parent_id, $user->role_type,$is_dow,$low_user_id);
        }
        //级别不能小于默认级别
        if($user->role <= $user->default_role){
            if($user_id == 1){
                return 0;
            }
            return $this->promotion_dow($user->parent_id, $user->role_type,$is_dow,$low_user_id);
        }
        $s = '%/' . $low_user_id . '/%';
        $sonShareAll = (new ShareUser())->where('role_url', 'like', $s)->whereOr(['user_id' => $low_user_id])
            ->order("role desc")
            ->find();
        if ($role_type == 1) {

            $temp_role = $user->role1;
            if ($temp_role != $sonShareAll['role']) {
                $user->role1 = $sonShareAll['role'];
                $user->save();
            }
        }

        if ($role_type == 2) {
            $temp_role = $user->role2;
            if ($temp_role != $sonShareAll['role']) {
                $user->role2 = $sonShareAll['role'];
                $user->save();
            }
        }

        if ($role_type == 3) {
            $temp_role = $user->role3;
            if ($temp_role != $sonShareAll['role']) {
                $user->role3 = $sonShareAll['role'];
                $user->save();
            }
        }

        // 上级用户
        $temp_user = (new ShareUser())->get(['user_id' => $user_id]); // 重新查询


        $ShareConfig = ShareConfig::where(['role' => $temp_user->role, 'type' => 2])->find();
        $ShareConfigList = ShareConfig::where(['type' => 2])->select();
        //三条线的级别和人数 有一个不够降级
        if($user_id == 20140){
            file_put_contents($user_id.'tt.txt',$temp_user->role."_".$temp_user->role1."_".$temp_user->role2."_".$temp_user->role3."_".$user->amount."_".(int)$ShareConfig['reward']);
        }

        $is_dow= 0;
        if ((($temp_user->role - $temp_user->role1) > 1 ||
                ($temp_user->role - $temp_user->role2) > 1 ||
                ($temp_user->role - $temp_user->role3) > 1) || ($user->amount < (int)$ShareConfig['reward'])) {
            $a = $temp_user->role1;
            $b = $temp_user->role2;
            $c = $temp_user->role3;
            $d = $a < $b ?($a> $c ? $c : $a) :($b > $c? $c : $b);
            $r = $d + 1;//通过顶级判断
            $p = 0;//通过人数判断
            foreach ($ShareConfigList as $k=>$v){
                if($user->amount > $v['reward']){
                    continue;
                }else{
                    $p = $v['role'] - 1;
                }
            }
            $end_role = $r > $p?$p:$r;
            $temp_user->role = $end_role > $temp_user->default_role?$end_role:$temp_user->default_role;
            $temp_user->save();
            $is_dow= 1;
        }
        return $this->promotion_dow($user->parent_id, $user->role_type,$is_dow,$user->user_id);
    }
}
